package com.presto.directo.mvvm.viewmodel

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.presto.directo.entity.CityEntity
import com.presto.directo.entity.PersonInfoEntity
import com.presto.directo.net.getHttpMap
import com.presto.directo.net.sign
import com.presto.directo.utils.*

class AddressViewModel(application: Application) : BaseViewModel(application) {

    val cityUpdateLiveData = MutableLiveData<Any>()
    val infoLiveData = MutableLiveData<PersonInfoEntity>()
    val uploadLiveData = MutableLiveData<Any>()
    val regionMap = mutableMapOf<String, List<CityEntity>?>()
    var postCode = ""
    var regionId1 = ""
    var regionId2 = ""
    var regionId3 = ""

    fun getInfo() {
        start(onNext = {
            showProgress()
            getApiService().getCityInfo(getHttpMap().sign(13)).getResultOrNull()?.let {
                postCode = it.post_code
                regionId1 = it.region_1
                regionId2 = it.region_2
                regionId3 = it.region_3
                infoLiveData.value = it
            }
        }, onComplete = {
            dismissProgress()
        })
    }

    fun getCity(postCode: String) {
        start(onNext = {
            val map = getHttpMap()
            map["cp"] = postCode
            val list = getApiService().getCityList(map.sign(29)).getResultOrNull()
            regionMap[postCode] = list
            cityUpdateLiveData.value = true
        }, toast = false)
    }

    fun upload(map: MutableMap<String, Any?>) {
        start(onNext = {
            showProgress()
            getApiService().saveCityInfo(map.sign(12)).getResultOrNull()
            uploadLiveData.value = true
        }, onComplete = {
            dismissProgress()
        })
    }

}